import modelExtend from 'dva-model-extend'
import { pathMatchRegexp } from 'utils'
import { <#list fields as field><#if (field.type=='DataList')>get${field.name?cap_first}Combo,</#if></#list>get${api?cap_first},create${api?cap_first},update${api?cap_first} } from 'api'
import { model } from 'utils/model'
import { message } from 'antd'

export default modelExtend(model, {
	namespace: '${namespace}',

	state: {
		${api}: {},<#list fields as field><#if (field.type=='DataList')>
		${field.name}Combo:[],</#if></#list>
	},

	subscriptions: {
		setup({ dispatch, history }) {
			history.listen(location => {
				let match=pathMatchRegexp('${url}', location.pathname)
				if (match) {
					if(match[1]!=0){
						const payload = {id:match[1]}
						dispatch({type: 'get',payload})
					}
					<#list fields as field><#if (field.type=='DataList')>
					dispatch({
						type: 'get${field.name?cap_first}Combo',
						payload,
					})
					</#if></#list>
				}
			})
		},
	},

	effects: {
		*get({ payload = {} }, { call, put }) {
			const data = yield call(get${api?cap_first}, payload)
			const {error,result}=data
			if (!error) {
				yield put({
					type: 'updateState',
					payload: {
						${api}: result,
					},
				})
			}
		},
		
		<#list fields as field><#if (field.type=='DataList')>
		*get${field.name?cap_first}Combo({ payload = {} }, { call, put }) {
			const data = yield call(get${field.name?cap_first}Combo, payload)
			const {error,result}=data
			if (!error) {
				yield put({
					type: 'updateState',
					payload: {
						${field.name}Combo:result
					},
				})
			}
		},
		</#if></#list>

		*create({ payload }, { call, put }) {
			const ${api} = yield select(({ ${namespace} }) => ${namespace}.${api})
			const data = yield call(create${api?cap_first}, ${api})
			if (!data.error) {
				message.success('操作成功')
				yield put({ type: 'hideModal' })
			} else {
				throw data
			}
		},

		*update({ payload }, { select, call, put }) {
			const ${api} = yield select(({ ${namespace} }) => ${namespace}.${api})
			const data = yield call(update${api?cap_first}, ${api})
			if (!data.error) {
				message.success('操作成功')
				yield put({ type: 'hideModal' })
			} else {
				throw data
			}
		},
		
	},

	reducers: {
		
	},

})